#define _CRT_SECURE_NO_WARNINGS 1
#include"SList.h"

SLNode* SLCreatNode(SLNDataType x) {
	SLNode* newnode = (SLNode*)malloc(sizeof(SLNode));
	if (newnode == NULL) {
		perror("malloc fail\n");
		return;
	}
	newnode->val = x;
	newnode->next = NULL;
	return newnode;
}
void SLPrint(SLNode* phead) {
	SLNode* cur = phead;
	while (cur)
	{
		printf("%d->", cur->val);

		cur = cur->next;
	}
	printf("NULL\n");
}
void SLPushBack(SLNode** pphead, SLNDataType x) {
	assert(pphead);
	SLNode* newnode = SLCreatNode(x);
	if (*pphead == NULL) {
		*pphead =newnode;
	}
	else {
		SLNode* cur = *pphead;
		while (cur->next)
		{
			cur = cur->next;
		}
		cur->next = newnode;
	}
	
}
void SLPushFront(SLNode** pphead, SLNDataType x) {
	assert(pphead);
	SLNode* newnode = SLCreatNode(x);

	newnode->next = *pphead;
	*pphead = newnode;

}

void SLPopBack(SLNode** pphead) {
	assert(pphead);
	assert(*pphead);
	if ((*pphead)->next == NULL) {
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLNode* prev = NULL;
		SLNode* cur = *pphead;
		while (cur->next)
		{
			prev = cur;
			cur = cur->next;
		}
		prev->next = cur->next;
		free(cur);
		cur = NULL;
	}
	
}
void SLPopFront(SLNode** pphead) {
	assert(pphead);
	assert(*pphead);
	
		SLNode* cur = *pphead;
		*pphead = (*pphead)->next;
		free(cur);
		cur = NULL;
}
SLNode*  SLFind(SLNode* phead, SLNDataType x) {
	while (phead)
	{
		if (phead->val == x) {
			return phead;
		}
		phead = phead->next;
	}
	return NULL;
}
void SLInsert(SLNode** pphead, SLNode* pos, SLNDataType x) {
	assert(pphead);
	assert(pos);
	SLNode* newnode = SLCreatNode(x);
	SLNode* prev = *pphead;
	while (prev->next!=pos)
	{
		prev = prev->next;
	}
	prev->next = newnode;
	newnode->next = pos;
}
void SLErase(SLNode** pphead, SLNode* pos) {
	assert(pphead);
	assert(*pphead);
	assert(pos);
	SLNode* prev = *pphead;
	while (prev->next != pos)
	{
		prev = prev->next;
	}
	prev->next = pos->next;
	free(pos);
	pos = NULL;
}

void SLInsertAfter(SLNode* pos, SLNDataType x) {
	assert(pos);
	SLNode* newnode = SLCreatNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}
void SLEraseAfter(SLNode* pos) {
	assert(pos);
	SLNode* tmp = pos->next;
	pos->next = tmp->next;
	free(tmp);
	tmp = NULL;
}
void SLDestroy(SLNode** pphead) {
	assert(pphead);
	SLNode* cur = *pphead;
	while (cur)
	{
		SLNode* next = cur->next;
		free(cur);
		cur = next;
	}
	*pphead = NULL;
}